package com.fysports.framework.log;

import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.fysports.web.config.AppConst;
import org.apache.log4j.PropertyConfigurator;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Properties;


/**
 * 通过Listener 设置log4j日志的相对目录
 * Date : 14-7-30 上午11:48
 * Project : JdmData_WebServer
 */
public class Log4jInitListener implements ServletContextListener {

    private static Log log = Log.getLog(Log4jInitListener.class);


    // 销毁
    public void contextDestroyed(ServletContextEvent event) {
        // ServletContext context = event.getServletContext();
    }


    // 启动加载
    public void contextInitialized(ServletContextEvent event) {
        ServletContext context = event.getServletContext();
        String path = context.getRealPath("/");
        String file = context.getInitParameter("log4j_init_path");
        String logFile = context.getInitParameter("log4j_file_path");
        if (file != null) {
            try {
                //使用Jfinal 1.9中的propkit功能
                Properties prop = PropKit.use(AppConst.CONFIG_LOG4J).getProperties();
                //                prop.load(new FileInputStream(path+file)); //加载log4j.properties
                prop.setProperty("log4j.appender.file.File",
                        path + logFile + prop.getProperty("log4j.appender.file.File")); //设置日志文件的输出路径
                PropertyConfigurator.configure(prop); //加载配置项
            }
            catch (Exception e) {
                log.error("初始化log4j日志输入路径异常，请检查web.xml参数配置是否正常，异常发生在" + this.getClass().getName()
                        + "类的public void init()方法，异常的愿意是：" + e.getMessage(), e.fillInStackTrace());
            }
        }
    }
}
